package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    public void  saveOrUpdate(Role entity) {
        if (entity.getId() == null) {
            roleMapper.insert(entity);
        } else {
            // 删除 role_menu
            roleMapper.deleteMenuRelation(entity.getId());
            // 删除 role_permission
            roleMapper.deletePermissionRelation(entity.getId());
            roleMapper.updateByPrimaryKey(entity);
        }
        // 维护 role_permission
        List<Permission> permissions = entity.getPermissions();
        for (Permission per : permissions) {
            roleMapper.insertPermissionRelation(entity.getId(), per.getId());
        }
        // 维护 role_menu
        List<Menu> menus = entity.getMenus();
        for (Menu menu : menus) {
            roleMapper.insertMenuRelation(entity.getId(), menu.getId());
        }
    }

    public int delete(Long id) {
        // 删除 role_menu
        roleMapper.deleteMenuRelation(id);
        // 删除 role_permission
        roleMapper.deletePermissionRelation(id);
        return roleMapper.deleteByPrimaryKey(id);
    }

    public Role get(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    public List<Role> listAll() {
        return roleMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {
        int count = roleMapper.queryCount(qo);
        if (count == 0) {
            return new PageResult(0, Collections.emptyList());
        }
        List<Role> roles = roleMapper.queryList(qo);
        return new PageResult(count, roles);
    }


    @Override
    public boolean validateUsernname(String name, Long id) {
        Role emp = roleMapper.selectByName(name);
        return emp == null || emp.getId() == id;
    }

    @Override
    public List<Long> selectByEmployeeId(Long employeeId) {
        return roleMapper.selectByEmployeeId(employeeId);
    }

    @Override
    public List<String> getSnByEmployeeId(Long employeeId) {
        return roleMapper.selectSnByEmployeeId(employeeId);
    }

}
